package com.leslie.hhcommunity.controller;

import com.leslie.hhcommunity.annotation.LoginRequired;
import com.leslie.hhcommunity.entity.User;
import com.leslie.hhcommunity.service.FollowService;
import com.leslie.hhcommunity.service.LikeService;
import com.leslie.hhcommunity.service.UserService;
import com.leslie.hhcommunity.util.CommunityConstant;
import com.leslie.hhcommunity.util.CommunityUtil;
import com.leslie.hhcommunity.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.controller
 * @ClassnName:UserController
 * @Description:
 * @Date 2022/1/2  21:14
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

	@Value("${community.path.upload}")
	private String uploadPath;

	@Value("${community.path.domain}")
	private String domain;

	@Value("${server.servlet.context-path}")
	private String contextPath;

	@Autowired
	HostHolder hostHolder;
	@Autowired
	UserService userService;
	@Autowired
	LikeService likeService;
	@Autowired
	FollowService followService;

	/**
	 * 跳转设置页面
	 *
	 * @return
	 */
//	@LoginRequired
	@RequestMapping("/setting")
	public String getSettingPage() {
		return "site/setting";
	}

//	@LoginRequired
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String uploadHeader(MultipartFile headerImage, Model model) {
		if (headerImage == null) {
			model.addAttribute("error", "您还没有选择图片！");
			return "site/setting";
		}
		//得到上传时的文件名
		String filename = headerImage.getOriginalFilename();
		//截取最后一个" ."以及后面的字符串
		String suffix = filename.substring(filename.lastIndexOf("."));
		if (StringUtils.isBlank(suffix)) {
			model.addAttribute("error", "文件格式不正确！");
			return "site/setting";
		}

		//生成随机文件名
		filename = CommunityUtil.generateUUID() + suffix;
		//确定文件存放的路径
		File dest = new File(uploadPath + "/" + filename);
		try {
			headerImage.transferTo(dest);
		} catch (IOException e) {
			LOGGER.error("上传文件失败：", e.getMessage());
			throw new RuntimeException("上传文件失败，服务器发生异常！", e);
		}

		// 更新当前用户头像的路径(web访问路径)
		// http://localhost:8080/community/user/header/xxx.png
		String headUrl = domain + contextPath + "/user/header/" + filename;
		User user = hostHolder.getUser();
		userService.updateHeader(user.getId(), headUrl);
		return "redirect:/index";
	}

	/**
	 * 返回用户头像
	 * 首页 头像这块通过 th:src="${loginUser.headerUrl}" 调用
	 * http://localhost:8080/community/user/header/8875b3caa3a5491c87a50ddaebc53418.png
	 * @param fileName
	 * @param response
	 */
	@RequestMapping("/header/{fileName}")
	public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
		// 服务器存放路径
		fileName = uploadPath + "/" + fileName;
		// 文件后缀
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		// 响应图片
		response.setContentType("image/" + suffix);

		try (
				FileInputStream fis = new FileInputStream(fileName);
				OutputStream os = response.getOutputStream();
		) {
			byte[] buffer = new byte[1024];
			int b = 0;
			while ((b = fis.read(buffer)) != -1) {
				os.write(buffer, 0, b);
			}
		} catch (IOException e) {
			LOGGER.error("读取文件失败：", e.getMessage());
		}
	}

	/**
	 * 个人主页
	 *
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequestMapping("/profile/{userId}")
	public String getProfilePage(@PathVariable("userId") int userId, Model model) {
		User user = userService.findUserById(userId);
		if (user == null) {
			throw new RuntimeException("该用户不存在");
		}
		//用户
		model.addAttribute("user", user);
		//点赞数量
		int likeCount = likeService.findUserLikeCount(userId);
		model.addAttribute("likeCount", likeCount);

		//关注数量                         这里传错id了，导致查到的是当前登录用户关注的人
//		long followeeCount = followService.findFolloweeCount(hostHolder.getUser().getId(), ENTITY_TYPE_USER);
		long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
		model.addAttribute("followeeCount", followeeCount);
		//粉丝数量
		long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
		model.addAttribute("followerCount", followerCount);
		//是否已关注
		boolean hasFollowed = false;
		if (hostHolder.getUser() != null) {
			hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
		}
		model.addAttribute("hasFollowed", hasFollowed);
		return "site/profile";
	}

}

